"""
python爬取网易云热歌榜歌曲

模块：
    requests   >>> pip install requests
    re
    os

- 数据来源：
    https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?ts=2765586
"""
import requests
import re
import os

fileName = 'img/'

# 如果想要爬取其他榜单的内容，只需要更改请求 url 查询参数的id即可
url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js'
# 请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/54.0.2840.99 Safari/537.36 "
}

params = {
    'ts': '2765586'
}


def save(hero_name, name, img_url):
    """保存皮肤"""
    filenames = f'{fileName}{hero_name}/'
    if not os.path.exists(filenames):
        os.makedirs(filenames)

    image_content = requests.get(url=img_url, headers=headers).content
    with open(filenames + name + '.jpg', mode='wb') as f:
        f.write(image_content)
        print(name)


response = requests.get(url=url, params=params, headers=headers)
heroes = response.json()['hero']
for hero in heroes:
    hero_id = hero['heroId']
    hero_url = f'https://game.gtimg.cn/images/lol/act/img/js/hero/{hero_id}.js'
    response_1 = requests.get(url=hero_url, headers=headers)
    # print(response_1.json())
    skins = response_1.json()['skins']
    for index in skins:
        hero_name = index['heroName']  # 绰号
        title = index['heroTitle']  # 安妮
        img_name = index['name']  # 皮肤名字
        img_url = index['mainImg']  # 皮肤图片url地址
        if img_url:
            save(hero_name, img_name, img_url)
        else:
            img_url = index['chromaImg']
            save(hero_name, img_name, img_url)
    # break
